/**
 * @description: vite自定义插件 - 校验依赖包本地版本与package.json版本是否一致(精确比对)
 * @author 叶花弈
 * @lastModify 2024-08-12
 */
import fs from "fs";
import path from "path";

export default (options = { verifyList: [] }) => {
  const { verifyList } = options;
  return {
    name: "vite-plugin-depend-version",
    configResolved(config) {
      console.log("\x1b[32m", `[插件: depVersion] - 正在校验依赖包本地版本与package.json版本是否一致...`);
      // 获取package.json下的依赖版本号
      const packagePath = path.resolve(config.root, "package.json");
      const packageContent = fs.readFileSync(packagePath, "utf8");
      const { dependencies, devDependencies } = JSON.parse(packageContent);
      const dep = { ...dependencies, ...devDependencies };
      // 比对需要校验的依赖
      for (const [packageName, packageVersion] of Object.entries(dep)) {
        if (!verifyList.includes(packageName)) continue;
        // 1.获取package.json中的依赖版本
        const version = /[~|^](.*)/g.exec(packageVersion)[1];
        // 2.获取node_modules中的依赖版本
        const nodeModulesVersion = JSON.parse(fs.readFileSync(`node_modules/${packageName}/package.json`, "utf-8")).version;
        if (nodeModulesVersion !== version) {
          throw new Error(`版本不一致: ${packageName} - package.json中版本: ${version}, 实际安装版本: ${nodeModulesVersion}`);
        }
      }
      console.log("\x1b[32m", `[插件: depVersion] √ 依赖包版本校验通过`);
    },
  };
};
